﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Threading;

namespace Lottery
{
    public partial class LotteryForm : Form
    {
        private Program.SubState lotteryState = Program.SubState.ZERO;
        private Program.SubState[] endState = { Program.SubState.ZERO, Program.SubState.TEN, Program.SubState.TEN, Program.SubState.FIVE, Program.SubState.THREE };
        private int[] endcount = { 0, 10, 10, 5, 3 };
        private int state;
        private Dictionary<string, List<string>> nowLuckyGuys;
        private System.Timers.Timer timer;
        private System.Timers.Timer timerMajor;
        private System.Timers.Timer timerPerson;
        private bool majorRandoming = false;
        private bool personRandoming = false;
        private bool auto = false;
        private int index = 0;
        private int refind = -1;
        private int width = 0;
        private int height = 0;
        private string luckGuy = "";
        private System.Media.SoundPlayer rollingPlayer;
        private System.Media.SoundPlayer commitPlayer;

        public LotteryForm(int state)
        {
            InitializeComponent();
            this.state = state;
            nowLuckyGuys = new Dictionary<string, List<string>>();
        }

        private void ControlInit()
        {
            for (int index = 0; index < endcount[state]; ++ index)
            {
                int x = 0, y = 0;
                PictureBox pb = new PictureBox();
                Label lb1 = new Label();
                Label lb2 = new Label();
                ((System.ComponentModel.ISupportInitialize)pb).BeginInit();
                this.SuspendLayout();

                //major
                lb1.AutoSize = true;
                lb1.Name = "lb1" + index.ToString();
                lb1.Size = new System.Drawing.Size(41, 12);
                lb1.TabIndex = 0;
                lb1.Text = "";
                lb1.BackColor = Color.Transparent;
                if (Program.state == Program.AppState.BEST)
                {
                    x = (this.Width - 140) / 2 + (index - 1) * 200 + (140 - lb1.Width) / 2;
                    y = this.label3.Height + 100 + 20 + 190;
                }
                else if (Program.state == Program.AppState.FIRST)
                {
                    x = (index % 5) * width + (width - lb1.Width) / 2;
                    y = this.label3.Height + 100 + 20 + 190;
                }
                else
                {
                    x = (index % 5) * width + (width - lb1.Width) / 2;
                    y = (index / 5) * (this.label1.Bottom - 50) + (height - 190) / 2 + 190 + 3 + this.label3.Height + 20;
                }
                lb1.Location = new System.Drawing.Point(x, y);
                //lb1.Visible = false;

                //person
                lb2.AutoSize = true;
                lb2.Name = "lb2" + index.ToString();
                lb2.Size = new System.Drawing.Size(41, 12);
                lb2.TabIndex = 0;
                lb2.Text = "";
                lb2.BackColor = Color.Transparent;
                if (Program.state == Program.AppState.BEST)
                {
                    x = (this.Width - 140) / 2 + (index - 1) * 200 + (140 - lb2.Width) / 2;
                    y = this.label3.Height + 100 + 40 + 190;
                }
                else if (Program.state == Program.AppState.FIRST)
                {
                    x = (index % 5) * width + (width - lb2.Width) / 2;
                    y = this.label3.Height + 100 + 20 + 190;
                }
                else
                {
                    x = (index % 5) * width + (width - lb2.Width) / 2;
                    y = (index / 5) * (this.label1.Bottom - 50) + (height - 190) / 2 + 6 + lb1.Height + 190 + this.label3.Height + 20;
                }
                lb2.Location = new System.Drawing.Point(x, y);
                //lb2.Visible = false;

                //picture
                if (Program.state == Program.AppState.BEST)
                {
                    x = (this.Width - 140) / 2 + (index - 1) * 200;
                    y = this.label3.Height + 100;
                }
                else if (Program.state == Program.AppState.FIRST)
                {
                    x = (index % 5) * width + (width - 140) / 2;
                    y = this.label3.Height + 100;
                }
                else
                {
                    x = (index % 5) * width + (width - 140) / 2;
                    y = (index / 5) * (this.label1.Bottom - 50) + (height - 190) / 2 + this.label3.Height + 20;
                }
                pb.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
                pb.Image = System.Drawing.Image.FromFile(@"image\temp.png");
                pb.Location = new System.Drawing.Point(x, y);
                pb.Name = "pb" + index.ToString();
                pb.Size = new System.Drawing.Size(140, 190);
                pb.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
                pb.TabIndex = 2;
                pb.TabStop = false;
                pb.BackColor = Color.Transparent;
                pb.Click += new System.EventHandler(refindPeople);
                //pb.Visible = false;

                this.Controls.Add(pb);
                this.Controls.Add(lb1);
                this.Controls.Add(lb2);
                ((System.ComponentModel.ISupportInitialize)pb).EndInit();
                this.ResumeLayout(false);
                this.PerformLayout();
            }
        }

        private void MajorTimerHandle(object o, System.Timers.ElapsedEventArgs e)
        {
            timerMajor.Stop();
            majorRandoming = false;

            //
            int real = (new Random(DateTime.Now.Millisecond)).Next(0, Program.temp.Count);
            string str = Program.temp[real];
            this.label1.Text = (Program.people2[str])[0];
            luckGuy = (Program.people2[str])[1];
            this.label1.Left = this.Width / 2 - 70 - this.label1.Width;
            this.label2.Visible = false;

            personRandoming = true;
            timerPerson.Start();
        }

        private void PersonTimerHandle(object o, System.Timers.ElapsedEventArgs e)
        {
            timerPerson.Stop();
            timer.Stop();
            personRandoming = false;
            this.label2.Visible = true;

            if (refind != -1)
            {
                this.label2.Text = luckGuy;
                this.label2.Left = this.Width / 2 + 70;

                commitPlayer.Play();

                DisplayForm form = new DisplayForm(this.label1.Text, this.label2.Text);
                form.ShowDialog();

                //change
                System.Windows.Forms.Control.ControlCollection cc = this.Controls;
                foreach (Control control in cc)
                {
                    if (control.Name == "pb" + refind.ToString())
                    {
                        ((PictureBox)control).Image = System.Drawing.Image.FromFile(@"photo\" + this.label1.Text + "_" + this.label2.Text + "_大小.jpg");

                          }
                    else if (control.Name == "lb1" + refind.ToString())
                    {
                        ((Label)control).Text = this.label1.Text;
                    }
                    else if (control.Name == "lb2" + refind.ToString())
                    {
                        ((Label)control).Text = this.label2.Text;
                    }
                }

                List<string> temp = new List<string>();
                temp.Add(this.label1.Text);
                temp.Add(this.label2.Text);
                nowLuckyGuys.Add(this.label1.Text + this.label2.Text, temp);
                deleteSingle(new KeyValuePair<string, List<string>>(label1.Text + label2.Text, temp));

                auto = false;
                refind = -1;
                this.label1.Text = "按回车键返回初始界面";
                this.label1.Left = (this.Width - this.label1.Width) / 2;
                this.label2.Visible = false;
            }
            else
            {

                //
                this.label2.Text = luckGuy;
                this.label2.Left = this.Width / 2 + 70;

                commitPlayer.Play();

                DisplayForm form = new DisplayForm(this.label1.Text, this.label2.Text);
                form.ShowDialog();
                ++this.lotteryState;
                AddPictureBox(index++, this.label1.Text, this.label2.Text);
                List<string> temp = new List<string>();
                temp.Add(label1.Text);
                temp.Add(label2.Text);
                nowLuckyGuys.Add(label1.Text + label2.Text, temp);
                deleteSingle(new KeyValuePair<string, List<string>>(label1.Text + label2.Text, temp));
                if (lotteryState == endState[state])
                {
                    auto = false;
                    this.label1.Text = "按回车键返回初始界面";
                    this.label1.Left = (this.Width - this.label1.Width) / 2;
                    this.label2.Visible = false;
                }
                else
                {
                    majorRandoming = true;
                    timerMajor.Start();
                    timer.Start();
                }
            }
        }

        private void LotteryForm_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            this.WindowState = FormWindowState.Maximized;
            timer = new System.Timers.Timer(40);
            timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerHandle);
            timerMajor = new System.Timers.Timer(3000);
            timerMajor.Elapsed += new System.Timers.ElapsedEventHandler(MajorTimerHandle);
            timerPerson = new System.Timers.Timer(1000);
            timerPerson.Elapsed += new System.Timers.ElapsedEventHandler(PersonTimerHandle);
            timer.AutoReset = true;

            rollingPlayer = new System.Media.SoundPlayer();
            rollingPlayer.SoundLocation = System.Environment.CurrentDirectory + @"\sound\rolling.wav";
            rollingPlayer.Load();
            commitPlayer = new System.Media.SoundPlayer();
            commitPlayer.SoundLocation = System.Environment.CurrentDirectory + @"\sound\commit.wav";
            commitPlayer.Load();

            string title = "";
            switch (Program.state)
            {
                case Program.AppState.THIRD:
                    title += "三等奖";
                    break;
                case Program.AppState.SECOND:
                    title += "二等奖";
                    break;
                case Program.AppState.FIRST:
                    title += "一等奖";
                    break;
                case Program.AppState.BEST:
                    title += "特等奖";
                    break;
                default:
                    break;
            }
            if (title != "特等奖")
            {
                switch (Program.substate)
                {
                    case Program.SubState.ONE:
                        title += "（一）";
                        break;
                    case Program.SubState.TWO:
                        title += "（二）";
                        break;
                    case Program.SubState.THREE:
                        title += "（三）";
                        break;
                    case Program.SubState.FOUR:
                        title += "（四）";
                        break;
                    case Program.SubState.FIVE:
                        title += "（五）";
                        break;
                    case Program.SubState.SIX:
                        title += "（六）";
                        break;
                    case Program.SubState.SEVEN:
                        title += "（七）";
                        break;
                    case Program.SubState.EIGHT:
                        title += "（八）";
                        break;
                    case Program.SubState.NINE:
                        title += "（九）";
                        break;
                    case Program.SubState.TEN:
                        title += "（十）";
                        break;
                    default:
                        break;
                }
            }
            this.label3.Text = title;
            this.label3.Left = (this.Width - this.label3.Width) / 2;

            this.width = this.Width / 5;
            this.height = (this.Height - this.label3.Height - 20) / 3;

            this.label1.Left = this.Width / 2 - 70 - this.label1.Width;
            this.label2.Left = this.Width / 2 + 70;
            this.label1.ForeColor = this.label2.ForeColor = Color.Red;

            this.label1.Top = this.label2.Top = (this.Height - this.label1.Height) / 2;
            if ((Program.state == Program.AppState.BEST) || (Program.state == Program.AppState.FIRST))
            {
                this.label1.Top = this.label2.Top = (this.Height - this.label1.Height) / 2 + 150;
            }

            ControlInit();
        }

        private int TempRandom()
        {
            if (majorRandoming)
            {
                return (new Random(DateTime.Now.Millisecond)).Next(0, Program.temp.Count);
            }
            else if (personRandoming)
            {
                return (new Random(DateTime.Now.Millisecond)).Next(0, Program.people[this.label1.Text].Count);
            }
            return (new Random(DateTime.Now.Millisecond)).Next();
        }

        protected void TimerHandle(object   source,   System.Timers.ElapsedEventArgs   e)
        {
            anotherHandler();
        }

        private void anotherHandler()
        {
            if (majorRandoming)
            {
                int number = TempRandom();
                string strtemp = Program.temp[number];
                this.label1.Text = (Program.people2[strtemp])[0]/*number.ToString()*/;
                this.label1.Left = this.Width / 2 - 70 - this.label1.Width;
                this.label2.Text = (Program.people2[strtemp])[1];
                this.label2.Left = this.Width / 2 + 70;
                //rollingPlayer.Play();
            }
            else if (personRandoming)
            {
                int number = TempRandom();
                //this.label2.Text = (Program.people[this.label1.Text])[number]/*number.ToString()*/;
                this.label2.Text = luckGuy;
                this.label2.Left = this.Width / 2 + 70;
            }
        }

        private void publish()
        {
            foreach (KeyValuePair<string, List<string>> pair in nowLuckyGuys)
            {
               WordPublishObject.Add(pair.Value[1], pair.Value[0], System.Environment.CurrentDirectory + @"\photo\" + pair.Value[0] + "_" + pair.Value[1] + "_大小.jpg");
        }
            FileInfo fi = new FileInfo("a.txt");
            if(fi.Exists)
            {
                WordPublishObject.Publish(System.Environment.CurrentDirectory + @"\pub\" + this.label3.Text, this.label3.Text, WordPublishObject.PublishMethod.Word);
            }
            else
            {
                WordPublishObject.Publish(System.Environment.CurrentDirectory + @"\pub\" + this.label3.Text, this.label3.Text, WordPublishObject.PublishMethod.Html);            
            }
           }

        private void deleteSingle(KeyValuePair<string, List<string>> person)
        {
            Program.people[person.Value[0]].Remove(person.Value[1]);
            Program.people2.Remove(person.Key);
            Program.temp.Remove(person.Key);
            if (Program.people[person.Value[0]].Count == 0)
            {
                Program.people.Remove(person.Value[0]);
            }
        }

        private void deleteDictionary()
        {
            foreach (KeyValuePair<string, List<string>> luckyGuy in nowLuckyGuys)
            {
                deleteSingle(luckyGuy);
            }
        }

        private void LotteryForm_KeyUp(object sender, KeyEventArgs e)
        {
            if (refind != -1)
            {
                //refindKeyHandle(sender, e);
                return;
            }
            if (e.KeyData == Keys.Escape && !auto)
            {
                Application.Exit();
            }
            if (e.KeyData == Keys.Return)
            {
                if ((lotteryState == endState[state]) && !auto)
                {
                    Thread thread = new Thread(new ThreadStart(publish));
                    thread.Start();
                    //deleteDictionary();
                    if (Program.substate == Program.endState[this.state])
                    {
                        ++Program.state;
                        Program.substate = Program.SubState.ONE;
                    }
                    else
                    {
                        ++Program.substate;
                    }
                    timer.Dispose();
                    timerMajor.Dispose();
                    timerPerson.Dispose();
                    this.Close();
                }
                else if (majorRandoming && !auto)
                {
                    majorRandoming = false;
                    personRandoming = true;
                    int real = (new Random(DateTime.Now.Millisecond)).Next(0, Program.temp.Count);
                    string str = Program.temp[real];
                    this.label1.Text = (Program.people2[str])[0];
                    luckGuy = (Program.people2[str])[1];
                    this.label1.Left = this.Width / 2 - 70 - this.label1.Width;
                    auto = true;
                    timerPerson.Start();
                }
                else if (personRandoming && !auto)
                {
                    personRandoming = false;
                    DisplayForm form = new DisplayForm(this.label1.Text, this.label2.Text);
                    form.ShowDialog();
                    ++this.lotteryState;
                    AddPictureBox(index++, this.label1.Text, this.label2.Text);
                    List<string> temp = new List<string>();
                    temp.Add(label1.Text);
                    temp.Add(label2.Text);
                    nowLuckyGuys.Add(label1.Text + label2.Text, temp);
                    deleteSingle(new KeyValuePair<string, List<string>>(label1.Text + label2.Text, temp));
                    this.label1.Text = "按回车键开始";
                    this.label2.Text = "按回车键开始";
                    this.label1.Left = this.Width / 2 - 70 - this.label1.Width;
                    this.label2.Left = this.Width / 2 + 70;
                    timer.Stop();
                    if (lotteryState == this.endState[this.state])
                    {
                        this.label1.Text = "按回车键返回初始界面";
                        this.label1.Left = (this.Width - this.label1.Width) / 2;
                        this.label2.Visible = false;
                    }
                }
                else
                {
                    majorRandoming = true;
                    timer.Start();
                }
            }
        }

        private void label1_ParentChanged(object sender, EventArgs e)
        {
        }

        private void label2_ParentChanged(object sender, EventArgs e)
        {
        }

        private void AddPictureBox(int index, string major, string person)
        {
            int x = 0, y = 0;
            foreach (Control control in this.Controls)
            {
                if (control.Name == "lb1" + index.ToString())
                {
                    ((Label)control).Text = major;
                    if (Program.state == Program.AppState.BEST)
                    {
                        x = (this.Width - 140) / 2 + (index - 1) * 200 + (140 - ((Label)control).Width) / 2;
                        y = this.label3.Height + 100 + 20 + 190;
                    }
                    else if (Program.state == Program.AppState.FIRST)
                    {
                        x = (index % 5) * width + (width - ((Label)control).Width) / 2;
                        y = this.label3.Height + 100 + 20 + 190;
                    }
                    else
                    {
                        x = (index % 5) * width + (width - ((Label)control).Width) / 2;
                        y = (index / 5) * (this.label1.Bottom - 50) + (height - 190) / 2 + 190 + 3 + this.label3.Height + 20;
                    }
                    ((Label)control).Location = new System.Drawing.Point(x, y);
                }
                else if (control.Name == "lb2" + index.ToString())
                {
                    ((Label)control).Text = person;
                    if (Program.state == Program.AppState.BEST)
                    {
                        x = (this.Width - 140) / 2 + (index - 1) * 200 + (140 - ((Label)control).Width) / 2;
                        y = this.label3.Height + 100 + 40 + 190;
                    }
                    else if (Program.state == Program.AppState.FIRST)
                    {
                        x = (index % 5) * width + (width - ((Label)control).Width) / 2;
                        y = this.label3.Height + 100 + 40 + 190;
                    }
                    else
                    {
                        x = (index % 5) * width + (width - ((Label)control).Width) / 2;
                        y = (index / 5) * (this.label1.Bottom - 50) + (height - 190) / 2 + 6 + ((Label)control).Height + 190 + this.label3.Height + 20;
                    }
                    ((Label)control).Location = new System.Drawing.Point(x, y);
                }
                else if (control.Name == "pb" + index.ToString())
                {
                    ((PictureBox)control).Image = System.Drawing.Image.FromFile(@"photo\" + major + "_" + person + "_大小.jpg");
                       }
            }
        }

        private void refindPeople(object sender, EventArgs e)
        {
            if ((Program.state != Program.AppState.THIRD) && (refind == -1) && (lotteryState == endState[state]))
            {
                foreach (KeyValuePair<string, List<string>> pair in nowLuckyGuys)
                {
                    if (pair.Key == this.label1.Text + this.label2.Text)
                    {
                        nowLuckyGuys.Remove(this.label1.Text + this.label2.Text);
                        break;
                    }
                }
                string name = ((PictureBox)sender).Name;
                refind = Convert.ToInt32(name.Substring(name.Length - 1, 1));
                majorRandoming = true;
                this.label1.Visible = this.label2.Visible = true;
                this.label1.Text = this.label2.Text = "按回车键开始";
                this.label1.Left = this.Width / 2 - 70 - this.label1.Width;
                this.label2.Left = this.Width / 2 + 70;
                majorRandoming = true;
                timer.Start();
                timerMajor.Start();
            }
        }

        private void refindKeyHandle(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Return)
            {
                if (majorRandoming)
                {
                    majorRandoming = false;
                }
                else if (personRandoming)
                {
                    timer.Stop();
                    foreach (KeyValuePair<string, List<string>> pair in nowLuckyGuys)
                    {
                        if (pair.Key == this.label1.Text + this.label2.Text)
                        {
                            nowLuckyGuys.Remove(this.label1.Text + this.label2.Text);
                            break;
                        }
                    }
                    DisplayForm form = new DisplayForm(this.label1.Text, this.label2.Text);
                    form.ShowDialog();

                    //change
                    System.Windows.Forms.Control.ControlCollection cc = this.Controls;
                    foreach(Control control in cc)
                    {
                        if (control.Name == "pb" + refind.ToString())
                        {
                         ((PictureBox)control).Image = System.Drawing.Image.FromFile(@"photo\" + this.label1.Text + "_" + this.label2.Text + "_大小.jpg");

                             }
                        else if (control.Name == "lb1" + refind.ToString())
                        {
                            ((Label)control).Text = this.label1.Text;
                        }
                        else if (control.Name == "lb2" + refind.ToString())
                        {
                            ((Label)control).Text = this.label2.Text;
                        }
                    }

                    List<string> temp = new List<string>();
                    temp.Add(this.label1.Text);
                    temp.Add(this.label2.Text);
                    nowLuckyGuys.Add(this.label1.Text + this.label2.Text, temp);
                    deleteSingle(new KeyValuePair<string, List<string>>(label1.Text + label2.Text, temp));

                    personRandoming = false;
                    refind = -1;
                    this.label1.Text = "按回车键返回初始界面";
                    this.label2.Visible = false;
                }
            }
        }
    }
}
